<template>
  <div>
    <apexchart
      ref="chartRef"
      type="bar"
      height="300"
      :options="chartOptions"
      :series="series"
    ></apexchart>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { statisticsService } from '@/services/analysis/statistics.service';
const props = defineProps({
  selectedEngineer: {
    type: Object,
    required: true,
  },
});

const chartOptions = ref({
  chart: { id: 'engineer-monthly-stats' },
  xaxis: {
    categories: [],
  },
  yaxis: [{ title: { text: '提交' } }, { opposite: true, title: { text: '代码' } }],
});
const series = ref([
  { name: '提交', data: [] },
  { name: '代码', data: [] },
]);

const chartRef = ref(null);

watch(
  () => props.selectedEngineer,
  async (newEngineer) => {
    if (newEngineer) {
      try {
        const data = await statisticsService.getEngineerMonthlyStats(newEngineer.id);
        const months = data.map((item) => item.month);
        const commits = data.map((item) => item.commitCount);
        const changes = data.map((item) => item.totalChanges);

        const averageCommits =
          commits.length > 0 ? commits.reduce((a, b) => a + b, 0) / commits.length : 0;
        const averageChanges =
          changes.length > 0 ? changes.reduce((a, b) => a + b, 0) / changes.length : 0;

        chartRef.value.updateOptions({
          title: {
            text: `${newEngineer.name} 的月度统计`,
            align: 'left',
          },
          xaxis: {
            categories: months,
          },
          annotations: {
            yaxis: [
              {
                y: averageCommits,
                borderColor: '#00E396',
                label: {
                  text: '平均提交: ' + averageCommits.toFixed(2),
                  borderColor: '#00E396',
                  style: {
                    color: '#fff',
                    background: '#00E396',
                  },
                },
              },
              {
                y: averageChanges,
                yAxisIndex: 1,
                borderColor: '#FEB019',
                label: {
                  text: '平均代码: ' + averageChanges.toFixed(2),
                  borderColor: '#FEB019',
                  style: {
                    color: '#fff',
                    background: '#FEB019',
                  },
                },
              },
            ],
          },
        });
        series.value[0].data = commits;
        series.value[1].data = changes;
      } catch (error) {
        console.error('Error fetching monthly stats:', error);
      }
    }
  },
  { immediate: true },
);
</script>
